package com.github.sbb.sherry.repository;

import com.github.sbb.sherry.common.collect.CollectionUtil;
import com.github.sbb.sherry.repository.entity.Fetcher;
import com.github.sbb.sherry.repository.entity.FetcherExample;
import com.github.sbb.sherry.repository.enums.DatasourceStatusEnum;
import com.github.sbb.sherry.repository.enums.DeleteFlagEnum;
import com.github.sbb.sherry.repository.mapper.FetcherMapper;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class FetcherRepository {

  @Resource
  private FetcherMapper mapper;

  public void addFetcher(Fetcher fetcher) {
    mapper.insertSelective(fetcher);
  }

  public Fetcher getByName(String name) {
    FetcherExample example = new FetcherExample();
    example.createCriteria().andNameEqualTo(name);
    return CollectionUtil.getFirstElseNull(mapper.selectByExample(example));
  }

  public long countByName(String name) {
    FetcherExample example = new FetcherExample();
    example.createCriteria().andNameEqualTo(name);
    return mapper.countByExample(example);
  }

  public List<Fetcher> getActiveFetchers() {
    FetcherExample example = new FetcherExample();
    example.createCriteria()
        .andStatusEqualTo(DatasourceStatusEnum.ACTIVE.getValue())
        .andDeleteFlagEqualTo(DeleteFlagEnum.NOT_DELETED.getValue());
    return mapper.selectByExample(example);
  }
}
